package api

import (
	"FeedXmh/app/dao"
	model2 "FeedXmh/app/model"
	"FeedXmh/hub"
	"FeedXmh/redis"
	"fmt"
	jwt "github.com/gogf/gf-jwt"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gtime"
	"github.com/gogf/gf/text/gstr"
	"github.com/gogf/gf/util/gconv"
)

var Device = device{}

type device struct {
}

func (a *device) Get(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}

	params := r.GetQueryMap()
	id := gconv.String(params["id"])

	houseid := gconv.String(params["houseid"])
	farmid := gconv.String(params["farmid"])
	remark := gconv.String(params["remark"])
	device_addr := gconv.String(params["device_addr"])
	device_type := gconv.String(params["device_type"])
	alive := gconv.String(params["alive"])
	key := gconv.String(params["key"])

	where := " 1=1 "
	if id != "" {
		where += " and id=" + id
	}
	if houseid != "" {
		where += " and houseid=" + houseid
	}
	if farmid != "" {
		where += " and farmid=" + farmid
	}
	if device_type != "" {
		where += " and device_type='" + device_type + "'"
	}
	if alive != "" {
		where += " and alive='" + alive + "'"
	}
	if remark != "" {
		where += " and remark like '%" + remark + "%' "
	}
	if device_addr != "" {
		where += " and device_addr like '%" + device_addr + "%' "
	}
	if key != "" {
		where += " and CONCAT(device_addr,remark) LIKE '%" + key + "%'"
	}

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	if dao.CheckApiPermission(url, r.Method, userid) {
		where += dao.SetPermisAddWhere(userid)
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		model := db.Model("v_device")
		records, error := model.Where(where).All()

		if error != nil {
			g.Log().Line().Error(error)
			res["msg"] = error.Error()
			res["code"] = -1
		} else {
			list := records.List()
			for i := 0; i < len(list); i++ {
				device_type := gconv.String(list[i]["device_type"])
				device_addr := gconv.String(list[i]["device_addr"])
				_p := g.Map{}
				_p["_page"] = 1
				_p["_limit"] = 1000000
				_p["clientid"] = fmt.Sprintf("cid_%s_%s", device_type, device_addr)
				devices, _ := hub.GetApiClients(_p)
				if len(devices) > 0 {
					//online
					list[i]["online"] = true
				} else {
					//offline
					list[i]["online"] = false
				}
				if device_type == model2.GW_MODE {
					list[i]["node_version"] = redis.GetGwAllNodeVersion(device_addr)
					list[i]["active_node_num"] = redis.GetGwNodeNum(device_addr)
					list[i]["online_node_num"] = redis.GetGwOnlineNodeNum(device_addr)
				}
			}
			res["data"] = list
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *device) GetByHouse(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}

	params := r.GetQueryMap()
	houseid := gconv.String(params["houseid"])

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path

	where := " 1=1 "

	if dao.CheckApiPermission(url, r.Method, userid) {
		if dao.IsAdmin(userid) || dao.IsService(userid) {
			where += fmt.Sprintf(" and houseid ='%s' ", houseid)
		} else {
			where += fmt.Sprintf(" and houseid='%s' ", houseid)
		}
		list, err := dao.T_device.GetList(where)
		if err != nil {
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			for i := 0; i < len(list); i++ {
				device_type := gconv.String(list[i]["device_type"])
				device_addr := gconv.String(list[i]["device_addr"])
				_p := g.Map{}
				_p["_page"] = 1
				_p["_limit"] = 1000000
				_p["clientid"] = fmt.Sprintf("cid_%s_%s", device_type, device_addr)
				devices, _ := hub.GetApiClients(_p)
				if len(devices) > 0 {
					//online
					list[i]["alive"] = 1
					list[i]["online"] = true
				} else {
					//offline
					list[i]["alive"] = 0
					list[i]["online"] = false
				}
			}
			res["code"] = 0
			res["data"] = list
			res["count"] = len(list)
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *device) GetPage(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}

	params := r.GetQueryMap()
	limit := r.GetInt("limit")
	page := r.GetInt("page")
	order := r.GetString("order")

	id := gconv.String(params["id"])
	houseid := gconv.String(params["houseid"])
	farmid := gconv.String(params["farmid"])
	remark := gconv.String(params["remark"])
	device_addr := gconv.String(params["device_addr"])
	device_type := gconv.String(params["device_type"])
	key := gconv.String(params["key"])

	where := " 1=1 "
	if id != "" {
		where += " and id=" + id
	}
	if houseid != "" {
		where += " and houseid=" + houseid
	}
	if farmid != "" {
		where += " and farmid=" + farmid
	}
	if device_type != "" {
		where += " and device_type='" + device_type + "'"
	}
	if remark != "" {
		where += " and remark like '%" + remark + "%' "
	}
	if device_addr != "" {
		where += " and device_addr like '%" + device_addr + "%' "
	}
	if key != "" {
		where += " and CONCAT(device_addr,remark) LIKE '%" + key + "%'"
	}

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	if dao.CheckApiPermission(url, r.Method, userid) {
		//管理员可以看到全部，其他角色按照权限获取
		where += dao.SetPermisAddWhere(userid)
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		model := db.Model("v_device")
		count, err := model.Where(where).Count()
		if err != nil {
			g.Log().Line().Error(err)
			res["msg"] = err.Error()
			res["code"] = -1
		} else {
			res["count"] = count
			start := limit*page - limit
			if start < 0 {
				start = 0
			}
			if order != "" {
				model = model.Order(order)
			}
			records, error := model.Limit(start, limit).All()
			if error != nil {
				g.Log().Line().Error(error)
				res["msg"] = error.Error()
				res["code"] = -1
			} else {
				list := records.List()
				for i := 0; i < len(list); i++ {

					device_type := gconv.String(list[i]["device_type"])
					device_addr := gconv.String(list[i]["device_addr"])
					_p := g.Map{}
					_p["_page"] = 1
					_p["_limit"] = 1000000
					_p["clientid"] = fmt.Sprintf("cid_%s_%s", device_type, device_addr)
					devices, _ := hub.GetApiClients(_p)
					if len(devices) > 0 {
						//online
						list[i]["online"] = true
					} else {
						//offline
						list[i]["online"] = false
					}

					if device_type == model2.GW_MODE {
						list[i]["node_version"] = redis.GetGwAllNodeVersion(device_addr)
						list[i]["active_node_num"] = redis.GetGwNodeNum(device_addr)
						list[i]["online_node_num"] = redis.GetGwOnlineNodeNum(device_addr)
					}

					//对应已经分配的用户
					//_addr := gconv.String(list[i]["device_addr"])
					//list[i]["userids"] = dao.GetDeviceUser(_addr)
				}

				res["code"] = 0
				res["data"] = list
			}
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *device) Post(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}

	params := r.GetFormMap()
	device_addr := gconv.String(params["device_addr"])
	device_type := gconv.String(params["device_type"])
	//remark := gconv.String(params["remark"])

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	if dao.CheckApiPermission(url, r.Method, userid) {
		gs, _ := dao.T_device.GetList(fmt.Sprintf(" device_addr='%s' and device_type='%s' ", device_addr, device_type))
		if len(gs) > 0 {
			res["code"] = -1
			res["msg"] = "系统已经存在该设备"
		} else {
			delete(params, "id")
			//params["lasttime"] = gtime.Now().String()
			//db:=g.DB(g.Cfg().GetString("custom.db_name"))
			//_, err :=db.Exec(fmt.Sprintf("update device_addr='%s' and device_type='%s' and remark='%s' where id=%s",device_addr,device_type,remark))
			_, err := dao.T_device.Save(params)
			if err != nil {
				res["code"] = -1
				res["msg"] = err.Error()
			} else {
				res["code"] = 0
				res["msg"] = ""
			}
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *device) Put(r *ghttp.Request) {

	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}

	params := r.GetFormMap()

	id := gconv.String(params["id"])
	houseid := gconv.String(params["houseid"])
	device_addr := gconv.String(params["device_addr"])
	device_type := gconv.String(params["device_type"])
	remark := gconv.String(params["remark"])
	default_hnum_prefix := gconv.String(params["default_hnum_prefix"])
	node_num := gconv.String(params["node_num"])

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	if dao.CheckApiPermission(url, r.Method, userid) {
		gs, _ := dao.T_device.GetList(fmt.Sprintf(" device_addr='%s' and device_type='%s' and id!=%s", device_addr, device_type, id))

		if len(gs) > 0 {
			res["code"] = -1
			res["msg"] = "系统已经存在该设备"
		} else {
			//params["create_date"] = gtime.Now().String()
			//_, err := dao.B_device.Save(params)
			db := g.DB(g.Cfg().GetString("custom.db_name"))
			_, err := db.Exec(fmt.Sprintf("update t_device set houseid='%s',device_addr='%s' , device_type='%s' , remark='%s',default_hnum_prefix='%s',node_num=%s where id=%s", houseid, device_addr, device_type, remark, default_hnum_prefix, node_num, id))
			if err != nil {
				res["code"] = -1
				res["msg"] = err.Error()
			} else {
				res["code"] = 0
				res["msg"] = ""
			}
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *device) Delete(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}
	params := r.GetFormMap()
	id := gconv.String(params["id"])

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	if dao.CheckApiPermission(url, r.Method, userid) {
		_, err := dao.T_device.Delete(" id=" + id)
		if err != nil {
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			res["code"] = 0
			res["msg"] = ""
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *device) GetForAllocate(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}

	where := " IFNULL(houseid,'')='' "

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	if dao.CheckApiPermission(url, r.Method, userid) {
		list, err := dao.T_device.GetList(where)

		if err != nil {
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			res["code"] = 0
			res["data"] = list
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *device) Allocate(r *ghttp.Request) {

	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}

	params := r.GetFormMap()

	claims := jwt.ExtractClaims(r)
	current_user := claims["userid"].(string)

	//id := gconv.String(params["id"])
	device_addr := gconv.String(params["device_addr"])
	userids := gconv.String(params["users"])

	url := r.URL.Path
	if dao.CheckApiPermission(url, r.Method, current_user) {
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		if tx, err := db.Begin(); err == nil {
			_, err = tx.Model("t_user_device").Where("device_addr=?", device_addr).Delete()
			if err == nil {
				if userids != "" {
					var _list gdb.List
					_userids := gstr.Split(userids, ",")
					for _, userid := range _userids {
						_item := gdb.Map{
							"userid":      userid,
							"device_addr": device_addr,
							"create_date": gtime.Now().String(),
							"create_user": current_user,
						}
						_list = append(_list, _item)
					}
					if len(_list) > 0 {
						_, err = tx.Model("t_user_device").Data(_list).Save()
					}
				}
			}
			if err != nil {
				tx.Rollback()
				res["code"] = -1
				res["msg"] = err.Error()
			} else {
				tx.Commit()
				res["code"] = 0
				res["msg"] = "保存成功"
			}
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *device) Query(r *ghttp.Request) {
	d := g.Map{
		"type": "",
		"data": nil,
	}
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": d,
	}

	params := r.GetQueryMap()
	sn := gconv.String(params["sn"])

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	if dao.CheckApiPermission(url, r.Method, userid) {
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		model := db.Model("v_device")
		data, error := model.Where("device_addr=?", sn).All()

		if error != nil {
			g.Log().Line().Error(error)
			res["msg"] = error.Error()
			res["code"] = -1
		} else {
			list := data.List()
			if len(list) > 0 {
				d["type"] = "gw"
				d["data"] = list[0]
				res["data"] = d
			} else {
				//查看饲喂器
				var feednode gdb.Map
				model := db.Model("v_hzgw_node")
				data, error = model.Where("sn=?", sn).All()
				if error != nil {
					g.Log().Line().Error(error)
					res["msg"] = error.Error()
					res["code"] = -1
				} else {
					list = data.List()
					if len(list) > 0 {
						feednode = list[0]
						addr := gconv.String(feednode["addr"])
						_, first_online := redis.GetGwNodeFirstOnline(addr, sn)
						feednode["first_online"] = first_online
						d["type"] = "feed"
						d["data"] = feednode
						res["data"] = d
					} else {
						//查询
						addr := redis.QuerySn(sn)
						if addr != "" {
							model := db.Model("v_device")
							data, error := model.Where("device_addr=?", addr).All()
							if error != nil {
								g.Log().Line().Error(error)
								res["msg"] = error.Error()
								res["code"] = -1
							} else {
								list = data.List()
								if len(list) > 0 {
									feednode = list[0]
									feednode["addr"] = feednode["device_addr"]
									feednode["sn"] = sn
									feednode["lasttime"] = ""
									feednode["version"] = ""
									feednode["hnum"] = redis.GetGwNodeHnum(addr, sn)
									_, first_online := redis.GetGwNodeFirstOnline(addr, sn)
									feednode["first_online"] = first_online
									d["type"] = "feed"
									d["data"] = feednode
									res["data"] = d
								}
							}
						} else {
							res["code"] = -1
							res["msg"] = "未查询到相关信息"
						}
					}

				}
			}
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}
